<?php

/**
 * grade_turma actions.
 *
 * @package    ibe
 * @subpackage grade_turma
 * @author     Creatix
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class grade_turmaActions extends sfActionsCreatix
{
  public function executeIndex(sfWebRequest $request)
  {
    return $this->forward('grade_turma', 'list');
  }
  
  public function executeImprimir(sfWebRequest $request)
  {
  	//GradeTurmaTable::carregarTurmaDia($request->getParameter('id_turma_ano_letivo'));
    	$this->grade	= GradeTurmaTable::carregarTurmaDia($request->getParameter('id_turma_ano_letivo'));//Doctrine::getTable('GradeTurma')->findByIdTurmaAnoLetivo($request->getParameter('id_turma_ano_letivo'));
		
//    	    	echo "<pre>";
//    	print_r($this->grade);
//    	die;
    	
    	$array_grade = array();
    	foreach($this->grade as $grade)
    	{
    		$array_grade[$grade['nu_dia_semana']][] = $grade;
    	}
    	
    	ksort($array_grade);
    	
    	sfLoader::loadHelpers('Partial');
		$dados = get_partial(
			'imprimir',
			array(
				'grade'			=> $array_grade
				)
		);

		$pdf	= new CreatixPDF('grade_horaria');
		$pdf->gerarPDF($dados, null, 'L');
    	
    	//$this->grade	= $array_grade;
  }
  
  public function executeGrade(sfWebRequest $request)
  {
  	$this->disciplinas	= Doctrine::getTable('Disciplina')->findAll(Doctrine::HYDRATE_ARRAY);
  	
  	$array_disciplina = array();
  	foreach($this->disciplinas as $disciplina)
  		$array_disciplina[] = array('value' => $disciplina['nm_disciplina'], 'id' => $disciplina['id_disciplina']);
  	
  	$this->disciplinas	= json_encode($array_disciplina);
  	
  	$this->docentes	= Doctrine::getTable('Docente')->findAll(Doctrine::HYDRATE_ARRAY);
  	
  	$array_docente = array();
  	foreach($this->docentes as $docente)
  		$array_docente[] = array('value' => $docente['nm_docente'], 'id' => $docente['id_docente']);
  
  	$this->docentes	= json_encode($array_docente);
  	
	$this->id_turma_ano_letivo	= $request->getParameter('id_turma_ano_letivo');
	$this->dia					= $request->getParameter('dia');
	
	$this->grade_turma				= GradeTurmaTable::carregarTurmaDia($this->id_turma_ano_letivo, $this->dia);
  	$this->form						= new GradeTurmaForm();
  }

	public function executeGrid()
	{
		//Recupero todas as informações necessárias para trabalhar com o grid
		$this->getRequestDataTable();
		$this->data					= GradeTurmaTable::consultar($this->filter, $this->order);
		$this->total_data			= count($this->data);
		$this->data					= $this->paginadorDataTable($this->data, $this->page_num, parent::LIMIT_PAGE_DATA_TABLE);

		sfLoader::loadHelpers(array('Url'));

	    foreach($this->data as $key => $r)
	    {
	    					    	$actions = array(
				'edit'	 => "<a href='".url_for($this->getModuleName().'/edit?id_grade_turma='.$r['id_grade_turma'])."' class='icoEditar'></a>",
				'delete' => "<a href='".url_for($this->getModuleName().'/delete?id_grade_turma='.$r['id_grade_turma'])."'  class='icoExcluir delete'></a>",
			);
																																																							    	$this->data[$key]['act'] = implode(' ', $actions);
    	}

		$this->setJSONDataTable($this->data, $this->colunas, $this->total_data);
		return sfView::NONE;
	}


    public function executeList()
    {
        $this->form = new GradeTurmaForm();
    	$this->colunas	= array(
    		      		$this->form['id_grade_turma']->renderLabel() => "id_grade_turma",
			      		$this->form['id_turma_ano_letivo']->renderLabel() => "id_turma_ano_letivo",
			      		$this->form['dt_grade']->renderLabel() => "dt_grade",
			      		$this->form['id_docente']->renderLabel() => "id_docente",
			      		$this->form['nu_hora_inicio']->renderLabel() => "nu_hora_inicio",
			      		$this->form['nu_hora_fim']->renderLabel() => "nu_hora_fim",
			      		$this->form['id_disciplina']->renderLabel() => "id_disciplina",
			      		$this->form['created_at']->renderLabel() => "created_at",
			      		$this->form['updated_at']->renderLabel() => "updated_at",
						"Ações"	=> "act"
		);

        $this->filter = $this->_getFilter();

        $this->setTemplate('index');
    }

    public function executeFilter()
	{
	    $filter = new Filtro(
			$this->getRequestParameter(sfActionsCreatix::FILTER_SESSION_USER_ATTRIBUTE)
		);

		$filter->setCulture($this->getUser()->getCulture());
		$this->getUser()->setAttribute('pg_num',1,$this->getModuleName());

		$this->getUser()->setAttribute(
			sfActionsCreatix::FILTER_SESSION_USER_ATTRIBUTE,
			serialize($filter),
			$this->getModuleName()
		);

		return $this->forward($this->getModuleName(), '/list');
	}

  public function executeNew(sfWebRequest $request)
  {
  	$this->id_turma_ano_letivo	= $request->getParameter('id_turma_ano_letivo');
  	$this->dia					= $request->getParameter('dia');
  	$this->form					= new GradeTurmaForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
  	
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
	
    $this->form = new GradeTurmaForm();

    $this->processForm($request, $this->form);
	return sfView::NONE;
   // $this->forward($this->getModuleName(), 'new');
  }

  public function validateCreate()
  {
  	return true;
  }

  public function handleErrorCreate()
  {
    return $this->forward($this->getModuleName(), 'new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($grade_turma = Doctrine::getTable('GradeTurma')->find(array($request->getParameter('id_grade_turma'))), sprintf('Object grade_turma does not exist (%s).', $request->getParameter('id_grade_turma')));
    $this->form = new GradeTurmaForm($grade_turma);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($grade_turma = Doctrine::getTable('GradeTurma')->find(array($request->getParameter('id_grade_turma'))), sprintf('Object grade_turma does not exist (%s).', $request->getParameter('id_grade_turma')));
    $this->form = new GradeTurmaForm($grade_turma);

    $this->processForm($request, $this->form);

    $this->forward($this->getModuleName(), 'edit');
  }

  public function validateUpdate()
  {
  	return true;
  }

  public function handleErrorUpdate()
  {
    return $this->forward($this->getModuleName(), 'edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    try
    {
    $request->checkCSRFProtection();

    $this->forward404Unless($grade_turma = Doctrine::getTable('GradeTurma')->find(array($request->getParameter('id_grade_turma'))), sprintf('Object grade_turma does not exist (%s).', $request->getParameter('id_grade_turma')));
    $grade_turma->delete();

    $this->redirect('grade_turma/index');
    }
    catch(Excepiton $e)
	{
		$this->getUser()->setFlash('erro', $e->getMessage());
    	$this->redirect('grade_turma/index');
	}

  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
  	try
  	{
  		$form				= $request->getParameter($form->getName());
  		
  		GradeTurma::deleteByTurma($form['id_turma_ano_letivo'], $form['nu_dia_semana']);
  		
		$form_hora_inicio	= $form['form_hora_inicio'];
		$form_hora_fim		= $form['form_hora_fim'];
		$form_id_disciplina	= $form['form_id_disciplina'];
		$form_id_docente	= $form['form_id_docente'];
  		
  		if(count($form_hora_inicio)
			&& count($form_hora_fim)
			&& count($form_id_disciplina)
			&& count($form_id_docente))
		{

			for($i=0; $i<4; $i++)
			{
				if($form_hora_inicio[$i] != ''
					&& $form_hora_fim[$i] != ''
					&& $form_id_disciplina[$i] != ''
					&& $form_id_docente[$i] != '')
				{
					$grade	= new GradeTurma();
					$grade->setNuHoraInicio(str_replace(":", "", $form_hora_inicio[$i]));
					$grade->setNuHoraFim(str_replace(":", "", $form_hora_fim[$i]));
					$grade->setNuDiaSemana($form['nu_dia_semana']);
					$grade->setIdDisciplina($form_id_disciplina[$i]);
					$grade->setIdDocente($form_id_docente[$i]);
					$grade->setIdTurmaAnoLetivo($form['id_turma_ano_letivo']);
					$grade->save();
					//parent::doSave($con);
				}
			}
		}
    }
    catch(Exception $e)
	{
		$output	= array('error' => $e->getMessage());
		return $this->renderText(json_encode($output));
	}
  }
}
